package com.lanou.renrenxin.tools;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.LocationMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.lanou.renrenxin.adapter.ChattingAdapter;
import com.lanou.renrenxin.dao.ChatList;
import com.lanou.renrenxin.singleton.RenrenxinSingleton;

import java.io.File;

/**
 * Created by zouhui on 16/3/9.
 */
public class SendMessage {
    private Handler handler;
    private ChattingAdapter adapter;
    private RecyclerView recyclerView;
    private Handler sendHandler;
    private ChattingAdapter.ChattingSendImageViewHolder sendImageViewHolder;


    public SendMessage(ChattingAdapter adapter, Handler handler, RecyclerView recyclerView) {
        this.adapter = adapter;
        this.handler = handler;
        this.recyclerView = recyclerView;
    }

    /**
     * 发送文本消息
     */
    public void sendTextMessage(final String sendMsgContent, final String mUsername, final String username, final String time) {
        final ChattingAdapter.ChattingSendViewHolder[] holder = new ChattingAdapter.ChattingSendViewHolder[1];
        final ChatList chat = new ChatList();
        chat.setMUsername(mUsername);
        chat.setUsername(username);
        chat.setTime(time);
        chat.setBody(sendMsgContent);
        chat.setType(0);
        chat.setMsg_type(StringValues.MSG_TYPE_TXT);
        adapter.send(chat);
        recyclerView.scrollToPosition(adapter.indexOfList(chat));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int index = adapter.indexOfList(chat);
                holder[0] = (ChattingAdapter.ChattingSendViewHolder)
                        recyclerView.findViewHolderForAdapterPosition(index);
                if (holder[0] == null) {
                } else {
                    handler.sendEmptyMessage(20);
                }


            }
        }).start();

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                String msgType = "";
                if (msg.what == 20) {
                    holder[0].progressBar.setVisibility(View.VISIBLE);
                    EMConversation conversation = EMChatManager.getInstance().getConversation(username);
                    //创建一条文本消息
                    EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
                    msgType = StringValues.MSG_TYPE_TXT;
                    //如果是群聊，设置chattype,默认是单聊
                    // 设置消息body
                    TextMessageBody txtBody = new TextMessageBody(sendMsgContent);
                    message.addBody(txtBody);
                    //设置接收人
                    message.setReceipt(username);
                    //把消息加入到此会话对象中
                    conversation.addMessage(message);
                    //发送消息
                    final String finalMsgType = msgType;
                    EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                        @Override
                        public void onSuccess() {
                            holder[0].progressBar.setVisibility(View.GONE);
                            RenrenxinSingleton.getInstence().saveChatList(
                                    mUsername, username, sendMsgContent, time, 2, 0, finalMsgType);
                        }

                        @Override
                        public void onError(int i, String s) {
                            holder[0].progressBar.setVisibility(View.GONE);
                            RenrenxinSingleton.getInstence().saveChatList(
                                    mUsername, username, sendMsgContent, time, 2, 1, finalMsgType);
                            LogUtils.e("******", "发送失败");
                        }

                        @Override
                        public void onProgress(int i, String s) {

                        }
                    });
                }
                return false;
            }
        });

    }


    /**
     * 发送图片
     *
     * @param filePath
     */
    public void sendImage(String filePath,String mUsername, final String username,String time) {
        final EMConversation conversation = EMChatManager.getInstance().getConversation(username);
        final EMMessage message = EMMessage.createSendMessage(EMMessage.Type.IMAGE);
        //如果是群聊，设置chattype,默认是单聊
        //message.setChatType(EMMessage.ChatType.GroupChat);

        final ImageMessageBody body = new ImageMessageBody(new File(filePath));
        // 默认超过100k的图片会压缩后发给对方，可以设置成发送原图
        // body.setSendOriginalImage(true);
        final ChatList chat = new ChatList();
        chat.setTime(time);
        chat.setMUsername(mUsername);
        chat.setUsername(username);
        chat.setMsg_type(StringValues.MSG_TYPE_IMAGE);
        chat.setBody(body.getLocalUrl());
        chat.setType(2);
        adapter.send(chat);
        recyclerView.scrollToPosition(adapter.getItemCount() - 1);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                message.addBody(body);
                message.setReceipt(username);
                conversation.addMessage(message);
                sendImageViewHolder = (ChattingAdapter.ChattingSendImageViewHolder)
                        recyclerView.findViewHolderForAdapterPosition(adapter.indexOfList(chat));
                Message message1 = new Message();
                message1.what = 230;
                message1.obj = sendImageViewHolder;
                handler.sendMessage(message1);
                EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onError(int i, String s) {

                    }

                    @Override
                    public void onProgress(int i, String s) {
                            Message msg = new Message();
                            msg.obj = i;
                            msg.what = 222;
                            handler.sendMessage(msg);


                    }
                });
            }
        }).start();
    }


    /**
     * 发送语音
     *
     * @param filePath
     * @param len
     */
    public void sendVoice(final String filePath, int len,String mUsername, final String username,RecorderVoice recorderVoice,String isSend) {
        final int lens[] = {len};

        if (!isSend.equals(filePath)) {
            final EMConversation conversation = EMChatManager.getInstance().getConversation(username);
            final EMMessage message = EMMessage.createSendMessage(EMMessage.Type.VOICE);
            //如果是群聊，设置chattype,默认是单聊
//        message.setChatType(ChatType.GroupChat);
            final ChatList chat = new ChatList();
            chat.setMsg_type(StringValues.MSG_TYPE_VOICE);
            chat.setMUsername(mUsername);
            chat.setType(2);
            chat.setVoiceLen(len);
            chat.setBody(recorderVoice.getPaths());
            chat.setUsername(message.getUserName());
            chat.setTime(FormatTime.formatTime(message.getMsgTime()));
            adapter.send(chat);
            recyclerView.scrollToPosition(adapter.indexOfList(chat));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    ChattingAdapter.ChattingSendVoiceViewHolder holder = (ChattingAdapter.ChattingSendVoiceViewHolder)
                            recyclerView.findViewHolderForAdapterPosition(adapter.indexOfList(chat));
                    if (handler != null) {
                        handler.sendEmptyMessage(21);
                    }
                }
            }).start();
            handler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    if (msg.what == 21) {
                        VoiceMessageBody body = new VoiceMessageBody(new File(filePath), lens[0]);
                        message.addBody(body);
                        message.setReceipt(username);
                        conversation.addMessage(message);
                        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                            @Override
                            public void onSuccess() {

                                handler.sendEmptyMessage(106);
                            }

                            @Override
                            public void onError(int i, String s) {

                            }

                            @Override
                            public void onProgress(int i, String s) {

                            }
                        });
                    }
                    return false;
                }
            });
            isSend = filePath;
        }

    }


    public void sendLocation(String locationAddress,double latitude,double longitude,String username,String mUsername){
        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.LOCATION);
//如果是群聊，设置chattype,默认是单聊
//        message.setChatType(EMMessage.ChatType.GroupChat);
        LocationMessageBody locBody = new LocationMessageBody(locationAddress, latitude, longitude);
        message.addBody(locBody);
        message.setReceipt(username);
        conversation.addMessage(message);
        EMChatManager.getInstance().sendMessage(message, new EMCallBack(){
            @Override
            public void onSuccess() {

            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }
}
